package com.example.makerspace.service.impl;

import com.alibaba.fastjson.JSON;
import com.example.makerspace.dto.Result;
import com.example.makerspace.model.ERNIEBotReqBody;
import com.example.makerspace.model.Message;
import com.example.makerspace.service.DreamService;
import com.example.makerspace.utils.BaiduUtils;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.MapUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.Optional;


@Service
public class DreamServiceImpl implements DreamService {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    public final static String GPT_PREFIX = "gpt_";

    @Override
    public void gpt(Map<String, Object> params, HttpServletResponse response) {
        String key = GPT_PREFIX + MapUtils.getString(params, "username");
        String content = MapUtils.getString(params, "content");
        String jsonStr = (String) redisTemplate.opsForValue().get(key);
        List<Message> messages =
                Optional.ofNullable(JSON.parseArray(jsonStr, Message.class)).orElse(Lists.newArrayList());
        Message m = new Message("user", content);
        messages.add(m);
        ERNIEBotReqBody ernieBotReqBody = new ERNIEBotReqBody();
        ernieBotReqBody.setMessages(messages);
        ernieBotReqBody.setStream(Boolean.TRUE);
        String json = JSON.toJSONString(ernieBotReqBody);
        String res = BaiduUtils.postEventStream(json, response);
        Message assistant = new Message("assistant", res);
        messages.add(assistant);
        String jsonString = JSON.toJSONString(messages);
        redisTemplate.opsForValue().set(key, jsonString);
    }

    @Override
    public Result clear(Map<String, Object> params) {
        String key = GPT_PREFIX + MapUtils.getString(params, "username");
        redisTemplate.delete(key);
        return Result.success();
    }

}
